package leetcode.sort;

import java.util.Comparator;
import java.util.HashMap;

import java.util.TreeSet;

/**
 给定一个字符串，请将字符串里的字符按照出现的频率降序排列。

 示例 1:

 输入:
 "tree"

 输出:
 "eert"

 解释:
 'e'出现两次，'r'和't'都只出现一次。
 因此'e'必须出现在'r'和't'之前。此外，"eetr"也是一个有效的答案。
 */
public class FrequencySort451 {
    public static void main(String[] args) {
        String str = "Aabb";
        String res = new FrequencySort451().frequencySort(str);
        System.out.println(res);
    }

    class Pair{
        private Character ch;
        private int fre;

        public Pair(Character ch, int fre) {
            this.ch = ch;
            this.fre = fre;
        }
    }
    public String frequencySort(String s) {
        TreeSet<Pair> set = new TreeSet<>(new Comparator<Pair>() {
            @Override
            public int compare(Pair o1, Pair o2) {
                if(o2.fre != o1.fre)
                    return o2.fre - o1.fre;
                else
                    return o1.ch - o2.ch;
            }
        });

        HashMap<Character, Integer> map = new HashMap<>();
        char[] chars = s.toCharArray();
        for (char c : chars) {
            if(map.containsKey(c)){
                Integer times = map.get(c);
                map.put(c,times+1);
            }else {
                map.put(c,1);
            }
        }
        for (Character c : map.keySet()) {
            set.add(new Pair(c,map.get(c)));
        }
        StringBuilder sb = new StringBuilder();
        for (Pair pair : set) {
            String ch = Character.toString(pair.ch);
            int fre = pair.fre;
            for (int i = 0; i < fre; i++) {
                sb.append(ch);
            }
        }
        return sb.toString();
    }

}